package com.shenchuangit.rydemo.util;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



public class ExcelUtils {

    private static final Logger logger = LoggerFactory.getLogger(ExcelUtils.class);

    private static final String XLS = ".xls";
    private static final String XLSX = ".xlsx";

    /**
     * 根据文件后缀获取对应Workbook对象
     *
     *      * @return
     */
    public static Workbook getWorkbook(MultipartFile excelFile) {
        Workbook workbook = null;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = (FileInputStream) excelFile.getInputStream();
                workbook = new XSSFWorkbook(fileInputStream);
        } catch (Exception e) {
            logger.error("获取文件失败", e);
        } finally {
            try {
                if (null != fileInputStream) {
                    fileInputStream.close();
                }
            } catch (Exception e) {
                logger.error("关闭数据流出错！错误信息：", e);
                return null;
            }
        }
        return workbook;
    }
    /**
     * 批量读取Excel文件，返回数据对象
     *
     * @param
     * @return
     */
    public static Map<String,Map<Long, BigDecimal>> readExcel(MultipartFile excelFile) {
        Workbook workbook = null;
        Map<String,Map<Long,BigDecimal>> resultMap;
        try {
           // String fileType = filePath.substring(filePath.lastIndexOf("."));
            workbook = getWorkbook(excelFile);
            if (workbook == null) {
                logger.info("获取workbook对象失败");
                return null;
            }
            resultMap = analysisExcel(workbook);
            return resultMap;
        } catch (Exception e) {
            logger.error("错误信息", e);
            return null;
        } finally {
            try {
                if (null != workbook) {
                    workbook.close();
                }
            } catch (Exception e) {

                logger.error("关闭数据流出错！错误信息：", e);
                return null;
            }

        }
    }

    /**
     * 解析Excel文件，返回数据对象
     *
     * @param workbook
     * @return
     */
    public static Map<String,Map<Long, BigDecimal>> analysisExcel(Workbook workbook) {
        Sheet sheet = workbook.getSheetAt(0);
        String sheetName = sheet.getSheetName();
        int rowEnd = 0;
        String excelType = "";
        if("资产负债表".equals(sheetName)){
            rowEnd = 125;
            excelType = "A";
        }
        if("利润表".equals(sheetName)){
            rowEnd = 67;
            excelType = "B";
        }
        if("现金流量表".equals(sheetName)){
            rowEnd = 59;
            excelType = "C";
        }
        int firstRowCount = sheet.getFirstRowNum();//获取第一行的序号
        //先获取年份
        Row rowYear = sheet.getRow(firstRowCount + 2);//
        List<Cell> yearCellList= new ArrayList<>();
        for(int i1 = 0 ; i1<4 ; i1++) {
            yearCellList.add(rowYear.getCell(i1+3));
        }
        int rowStart = firstRowCount + 4; //第四行是有效数据，从这里开始
        Row row;
        Map<String,Map<Long,BigDecimal>> resultMap = new HashMap<>();
        for(int i2 = 0; i2<4; i2++) {
            Map<Long,BigDecimal> resultYearMap = new HashMap<>();
            for(int j = rowStart; j<rowEnd+1 ; j++) {
                row = sheet.getRow(j);//获取数据行
                Cell cell1 = row.getCell(2); //行号
                String numberCellString = cell1.getNumericCellValue() + "";
                Long numberCell = null;
                if (!numberCellString.equals("")) {
                    numberCellString = numberCellString.substring(0, numberCellString.indexOf("."));
                    numberCell = Long.parseLong(numberCellString);
                }
                Cell cell2 = row.getCell(3 + i2);
                String valueCellString = cell2.getNumericCellValue() + "";
                if (!valueCellString.equals("") && !valueCellString.equals("0.0")) {
                    if (valueCellString.endsWith(".0")) {
                        valueCellString = valueCellString.substring(0, valueCellString.indexOf("."));
                    }
                    BigDecimal valueCell = new BigDecimal(valueCellString);
                    //用于保存到value表的单行数据信息
                    resultYearMap.put(numberCell, valueCell);
                }
            }
            Cell yearCell = yearCellList.get(i2);
            //key值保存 所属表格#所属年份 ,用于之后解析
            String symbolString;
            if(i2 != 3) {
                String year = yearCell.getNumericCellValue()+"";
                year = year.substring(0,year.indexOf("."));
                symbolString = excelType+"#"+year;
            }else{
                symbolString = excelType+"#"+yearCell.getStringCellValue();
            }

            resultMap.put(symbolString,resultYearMap);
        }
        return resultMap;
    }
}